package com.edu.controller;


import com.edu.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @RequestMapping("/register")
    public String register(User user){
        System.out.println(user);
        return "/index.jsp";
    }


    @RequestMapping("/test01")
    public String test01(User user){
        System.out.println(user);
        return "/index.jsp";
    }


    @RequestMapping("/register2")
    public String register2(@Valid User user, BindingResult bindingResult, Model model){
        if(bindingResult.hasErrors()){ //判断 校验中是否出错
            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
            Map<String,String> errors = new HashMap<>();
            for (FieldError fieldError : fieldErrorList) {
                String fieldName = fieldError.getField(); // 获取验证出错的属性的属性名
                String message = fieldError.getDefaultMessage(); // 获取默认的出错的信息提示
//                model.addAttribute("user",user);
                errors.put(fieldName,message);
            }
            model.addAttribute("errors",errors);
            return "forward:/register2.jsp";
        }
        return "/index2.jsp";
    }

    //注册
    @RequestMapping("/register3")
    public String register3(@Valid User user,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "/register3.jsp";
        }
        return "index.jsp";
    }

    //为了跳转到  带有spring标签的 jsp页面，并携带一个user对象
    @RequestMapping("/regPage")
    public String registerPage(User user){
        return "forward:register3.jsp";//必须使用转发
    }

}
